<script setup lang="ts">
import { ref } from "vue";
import { useStore } from "../../../utils/store";
import { v4 as uuidv4 } from "uuid";

let myMsg = ref("");
let myMsgRef = ref();

const store = useStore();

const onClick = () => {
  // 取值，两种方式相同
  myMsg.value = store.state.userName;
  myMsg.value = store.getters.getUserName;
  // 清除后返回 undefined
  console.log(store.state.userInfo.gender);
  // 读取 localStorage
  console.log(store.state.config.ver);
};

const onUpdate = () => {
  // 输出的是 input 标签
  console.log(myMsgRef.value);
  // 输出的是 input 标签的 value 属性
  store.commit("SET_USERNAME", myMsgRef.value.value);
  // 可以直接读写，不建议通过此种方式写入，无法存储到 sessionStorage
  store.state.userInfo.gender = store.state.userInfo.gender == 1 ? 2 : 1;
  // 推荐写入方式，可以存储到 sessionStorage，刷新页面仍然有效
  store.commit("SET_USERINFO", store.state.userInfo);

  store.state.config.ver = String(store.state.userInfo.gender);
  // 写入 localStorage
  store.commit("SET_CONFIG", store.state.config);

  store.state.token = uuidv4();
  // 写入 cookie
  store.commit("SET_TOKEN", store.state.token);
};

const onClear = () => {
  store.commit("SET_CLEAR_SESSION");
};
</script>
<template>
  <h1>vuex 状态管理 store、sessionStorage、localStorage、cookie、uuid</h1>
  <p>读取 store userName 的默认值：{{ myMsg }}</p>
  <p>
    读取 sessionStorage store.state.userInfo.gender 的默认值：{{
      store.state.userInfo.gender
    }}
  </p>
  <p>
    读取 localStorage store.state.config.ver 的默认值：{{
      store.state.config.ver
    }}
  </p>
  <p>读取 cookie store.token 的默认值：{{ store.state.token }}</p>
  <a href="javascript:void(0)" @click="onClick">读取</a>
  输入要更新 store 的值：
  <input ref="myMsgRef" /> &nbsp;
  <a href="javascript:void(0)" @click="onUpdate">更新</a> &nbsp;
  更新后点击读取刷新 &nbsp;
  <a href="javascript:void(0)" @click="onClear">清除缓存</a>
</template>
